package models

import (
	"github.com/jinzhu/gorm"
)

type Dept struct {
	ID       int    	`json:"dept_id"`
	DeptName string `json:"dept_name"`
}


func DeptInsert(d Dept) error {
	err := db.Create(&d).Error

	if err != nil {
		return err
	}

	return nil
}


// Selects 返回所有部门列表
func DeptSelects() ([]*Dept, error){
	var (
		d []*Dept
		ds []*Dept
	)

	err := db.Find(&ds).Error
	if err != gorm.ErrRecordNotFound && err != nil {
		return nil, err
	}

	for _, v := range ds {
		d = append(d, v)
	}

	return d, nil
}

// GetDeptNameById 根据部门ID返回该部门信息
func GetDeptNameById(deptId int) (*Dept, error){
	var d Dept
	err := db.Where("id = ?", deptId).Find(&d).Error
	if err != gorm.ErrRecordNotFound && err != nil {
		return nil, err
	}

	if d.ID > 0 {
		return &d, nil
	}

	return nil, nil
}

func CheckDeptIsExisted(deptName string) bool {
	var d Dept
	err := db.Where("dept_name = ?", deptName).Find(&d).Error

	if err == gorm.ErrRecordNotFound {
		return false
	}

	return true
}